const app = getApp()
const consumptionApi = require('../../api/consumption')

Page({
  data: {
    loading: false,
    records: [],
    hasMore: true,
    page: 1,
    size: 10,
    total: 0,
    
    // 筛选条件
    filterVisible: false,
    filterForm: {
      paymentMethod: '',
      status: '',
      packageName: '',
      startTime: '',
      endTime: ''
    },
    
    // 统计信息
    statistics: {
      totalAmount: '0.00',
      totalCount: 0,
      thisMonthAmount: '0.00',
      thisMonthCount: 0
    },
    
    // 支付方式选项
    paymentMethods: [
      { value: '', label: '全部' },
      { value: 'BALANCE', label: '余额支付' },
      { value: 'ALIPAY', label: '支付宝' },
      { value: 'WECHAT', label: '微信支付' }
    ],
    
    // 状态选项
    statusOptions: [
      { value: '', label: '全部' },
      { value: 0, label: '失败' },
      { value: 1, label: '成功' },
      { value: 2, label: '处理中' }
    ]
  },

  onLoad() {
    this.loadConsumptionRecords()
    this.loadStatistics()
  },

  onShow() {
    // 从其他页面返回时刷新数据
    this.refreshData()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 刷新数据
  async refreshData() {
    this.setData({
      page: 1,
      records: [],
      hasMore: true
    })
    await Promise.all([
      this.loadConsumptionRecords(),
      this.loadStatistics()
    ])
  },

  // 加载消费记录
  async loadConsumptionRecords() {
    if (this.data.loading) return
    
    this.setData({ loading: true })
    
    try {
      const params = {
        page: this.data.page,
        size: this.data.size
      }
      
      // 添加筛选条件
      const filter = this.data.filterForm
      if (filter.paymentMethod) params.paymentMethod = filter.paymentMethod
      if (filter.status !== '') params.status = filter.status
      if (filter.packageName) params.packageName = filter.packageName
      if (filter.startTime) params.startTime = filter.startTime
      if (filter.endTime) params.endTime = filter.endTime
      
      const data = await consumptionApi.getMyConsumptionRecordPage(params)
      
      if (data && data.records) {
        const newRecords = data.records.map(record => ({
          ...record,
          createTime: this.formatTime(record.createTime),
          consumeAmount: this.formatAmount(record.consumeAmount),
          statusName: this.getStatusName(record.status),
          paymentMethodName: this.getPaymentMethodName(record.paymentMethod)
        }))
        
        this.setData({
          records: this.data.page === 1 ? newRecords : [...this.data.records, ...newRecords],
          total: data.total || 0,
          hasMore: newRecords.length >= this.data.size
        })
      } else {
        this.setData({
          records: this.data.page === 1 ? [] : this.data.records,
          hasMore: false
        })
      }
    } catch (error) {
      console.error('加载消费记录失败:', error)
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载更多
  async loadMore() {
    this.setData({
      page: this.data.page + 1
    })
    await this.loadConsumptionRecords()
  },

  // 加载统计信息
  async loadStatistics() {
    try {
      const data = await consumptionApi.getMyConsumptionStatistics()
      if (data) {
        this.setData({
          statistics: {
            totalAmount: this.formatAmount(data.totalAmount || 0),
            totalCount: data.totalCount || 0,
            thisMonthAmount: this.formatAmount(data.thisMonthAmount || 0),
            thisMonthCount: data.thisMonthCount || 0
          }
        })
      }
    } catch (error) {
      console.error('加载统计信息失败:', error)
    }
  },

  // 显示筛选面板
  showFilter() {
    this.setData({ filterVisible: true })
  },

  // 隐藏筛选面板
  hideFilter() {
    this.setData({ filterVisible: false })
  },

  // 支付方式筛选改变
  onPaymentMethodChange(e) {
    const { value } = e.detail
    const selectedMethod = this.data.paymentMethods[value]
    this.setData({
      'filterForm.paymentMethod': selectedMethod.value
    })
  },

  // 状态筛选改变
  onStatusChange(e) {
    const { value } = e.detail
    const selectedStatus = this.data.statusOptions[value]
    this.setData({
      'filterForm.status': selectedStatus.value
    })
  },

  // 套餐名称输入改变
  onPackageNameInput(e) {
    const { value } = e.detail
    this.setData({
      'filterForm.packageName': value
    })
  },

  // 应用筛选
  applyFilter() {
    this.setData({
      page: 1,
      records: [],
      hasMore: true,
      filterVisible: false
    })
    this.loadConsumptionRecords()
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      filterForm: {
        paymentMethod: '',
        status: '',
        packageName: '',
        startTime: '',
        endTime: ''
      },
      page: 1,
      records: [],
      hasMore: true,
      filterVisible: false
    })
    this.loadConsumptionRecords()
  },

  // 查看记录详情
  viewDetail(e) {
    const { record } = e.currentTarget.dataset
    wx.showModal({
      title: '消费详情',
      content: `套餐：${record.packageName}\n金额：¥${record.consumeAmount}\n支付方式：${record.paymentMethodName}\n状态：${record.statusName}\n时间：${record.createTime}\n订单号：${record.orderNo}`,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  // 格式化金额
  formatAmount(amount) {
    if (!amount && amount !== 0) return '0.00'
    return parseFloat(amount).toFixed(2)
  },

  // 格式化时间
  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 一分钟内
    if (diff < 60000) {
      return '刚刚'
    }
    // 一小时内
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    }
    // 一天内
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    }
    // 一周内
    if (diff < 604800000) {
      return `${Math.floor(diff / 86400000)}天前`
    }
    
    // 超过一周显示具体日期
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    
    return `${month}-${day} ${hour}:${minute}`
  },

  // 获取状态名称
  getStatusName(status) {
    const statusMap = {
      0: '失败',
      1: '成功',
      2: '处理中'
    }
    return statusMap[status] || '未知'
  },

  // 获取支付方式名称
  getPaymentMethodName(method) {
    const methodMap = {
      'BALANCE': '余额支付',
      'ALIPAY': '支付宝',
      'WECHAT': '微信支付'
    }
    return methodMap[method] || method
  }
})
